"""
用户账户相关功能 注册 短信 登录 注销
"""
import datetime
from django.core.validators import RegexValidator
from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from django.db.models import Q
import uuid
from web import models
from web.forms.account import RegisterModelForm, Login_Form
from web import md5
# Create your views here.


def register(request):
    if request.method != 'POST':
        form = RegisterModelForm()
        return render(request, 'register.html', locals())
    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        # instance = form.save(),在数据库中新增一条数据，并将数据赋值给instance
        # 用户表中新建一条数据（注册）
        instance = form.save()

        # 创建交易记录
        policy_object = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
        models.Transaction.objects.create(
            status=2,
            order=str(uuid.uuid4()),
            user=instance,
            price_policy=policy_object,
            count=0,
            price=0,
            start_datetime=datetime.datetime.now()

        )

        return JsonResponse({'status':True, 'data':'/login/'})
    return JsonResponse({'status': False, 'error': form.errors})


def login(request):
    if request.method == 'GET':
        form = Login_Form(request)
        return render(request, 'login.html', locals())
    form = Login_Form(request,data=request.POST)
    if form.is_valid():
        # 登陆成功后放入session中
        name = form.cleaned_data['username']
        request.session['user'] = name
        return redirect('/index')
    return render(request, 'login.html', locals())


"""验证码"""
from io import BytesIO
from ..code import check_code
def img_code(request):
    img, code_str = check_code()
    request.session['img_code'] = code_str
    request.session.set_expiry(60)
    stream = BytesIO()
    img.save(stream, 'png')
    return HttpResponse(stream.getvalue())


def logout(request):

    request.session.clear()

    return redirect('/login')
